# -*- coding: utf-8 -*-

import os
import re
import time
import ppc
import ppc.pipe


class MatchFilter(ppc.pipe.Pipe):
    """匹配过滤器"""

    def handle(self):
        matchList = []
        if isinstance(self['match'], list):
            matchList = self['match']
        else:
            matchList.append(self['match'])

        flag = True
        for param in matchList:
            type = param['type'] if 'type' in param else 'equal'
            positive = True \
                if ('positive' not in param) or (param['positive'] == 'yes') \
                else False
            methodName = '_match{0}'.format(type.capitalize())
            if hasattr(self, methodName):
                method = getattr(self, methodName)
                m = method(param['for'], param['value'])
                if (positive and (not m)) or ((not positive) and m):
                    flag = False
                    break
            else:
                raise NotImplementedError(
                    'MatchFilter未实现名为{0}的匹配方法'.format(methodName))

        if flag:
            self.transfer(self.input)

    def _matchEqual(self, a, b):
        return a == b

    def _matchRegex(self, a, pattern):
        m = re.search(pattern, a)
        return True if m else False

    def _matchExtension(self, a, ext):
        ext = ext.replace(',', '|')
        pattern = "\.({0})$".format(ext)
        return self._matchRegex(a, pattern)


class FrequencyFilter(ppc.pipe.Pipe):
    """频次过滤器(某段时间只允许数据通过一次)"""

    def handle(self):
        if not hasattr(self, 'prev_timepoint'):
            self.prev_timepoint = 0

        now = time.time()
        span = int(self['timespan'].value)
        unit = self['timeunit'].value
        seconds = ppc.SECONDS_NUM[unit] * span

        if now - self.prev_timepoint >= seconds:
            self.prev_timepoint = now
            self.transfer(self.input)


class StepFilter(ppc.pipe.Pipe):
    """步幅过滤器(在一定范围内数值变化达到某一步幅，数据通过一次)"""

    def handle(self):
        from_ = int(self['from'].value)
        to_ = int(self['to'].value)
        step_ = abs(int(self['step'].value))
        var = int(self['var'].value)

        if not hasattr(self, 'prev_value'):
            self.prev_value = var

        if (from_ <= var <= to_ or from_ >= var >= to_) and \
                abs(var - self.prev_value) >= step_:
            self.prev_value = var
            self.transfer(self.input)
